package czy.demo.config;

import czy.demo.config.security.DefaultAuthenticationFailureHandler;
import czy.demo.config.security.DefaultAuthenticationSuccessHandler;
import czy.demo.config.security.DefaultLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final PasswordEncoder passwordEncoder = NoOpPasswordEncoder.getInstance();

    @Lazy
    @Autowired
    private SessionRegistry sessionRegistry;

    @Autowired
    private DefaultAuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private DefaultAuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private DefaultLogoutSuccessHandler logoutSuccessHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(passwordEncoder)
                .withUser("root").password("123456").roles("ADMIN","USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests();
        /** 替换登录过滤器 */
        http.csrf().disable();
        http.sessionManagement()
                .maximumSessions(5)
                .sessionRegistry(sessionRegistry);
        http.anonymous().disable();
        http.formLogin().loginProcessingUrl("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .permitAll();
        http.logout()
                .logoutUrl("/logout")
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .logoutSuccessHandler(logoutSuccessHandler);
        http.httpBasic().disable();

    }
}
